package com.xlh.wjdcserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.property.dto.AnswerDTO;
import com.property.dto.AnswerExportDTO;
import com.property.dto.AnswerPageDTO;
import com.property.entity.Answer;
import com.property.entity.Question;
import com.property.vo.AnswerPageVO;
import com.property.vo.AnswerVO;
import com.xlh.wjdcserver.mapper.AnswerMapper;
import com.xlh.wjdcserver.service.AnswerService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements AnswerService {
    @Override
    public void addAnswer(List<AnswerDTO> answerDTOs) {
        List<Answer> answerList = answerDTOs.stream().flatMap(answerDTO ->
                        answerDTO.getOptions().stream()
                                .map(optionDTO -> {
                                    Answer answer = new Answer();
                                    answer.setCommitId(UUID.randomUUID().toString().replace("-", "").substring(0,11));
                                    if(optionDTO.getOptionName().equals("TEXT"))
                                    {
                                        answer.setId("text-" + UUID.randomUUID().toString().replace("-", "").substring(0,9));
                                        answer.setText(optionDTO.getText());
                                        answer.setQid(answerDTO.getQid());
                                        answer.setQueId(answerDTO.getQueId());
                                        answer.setQueContent(answerDTO.getQueContent());
                                        answer.setUserId(answerDTO.getUserId());
                                        return answer;
                                    }
                                    BeanUtil.copyProperties(answerDTO, answer);
                                    BeanUtil.copyProperties(optionDTO, answer,"id");
                                    answer.setQid(answerDTO.getQid());
                                    answer.setQueId(answerDTO.getQueId());
                                    answer.setQueContent(answerDTO.getQueContent());
                                    answer.setOptName(optionDTO.getOptionName());
                                    answer.setOptContent(optionDTO.getOptionContent());
                                    answer.setOptId(optionDTO.getId());

                                    return answer;
                                }))
                .collect(Collectors.toList());
        baseMapper.insert(answerList);
    }

    @Override
    public Page<AnswerVO> listAnswer(AnswerPageDTO answerPageDTO) {
        Page<AnswerVO> page = new Page<>(answerPageDTO.getPage(), answerPageDTO.getSize());
        QueryWrapper<AnswerVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("que.q_id", answerPageDTO.getQid());
        if (answerPageDTO.getStartTime() != null)
        {
            queryWrapper.ge("a.create_time", answerPageDTO.getStartTime());
        }
        if (answerPageDTO.getEndTime() != null)
        {
            queryWrapper.le("a.create_time", answerPageDTO.getEndTime());
        }

        Page<AnswerVO> answerVOPage = baseMapper.page(page, queryWrapper);
        List<AnswerVO> records = answerVOPage.getRecords();
        Map<String,AnswerVO> map = new LinkedHashMap<>();
        records.forEach(answerVO -> {
            map.putIfAbsent(answerVO.getCommitId(), new AnswerVO());
            AnswerVO answerVO1 = map.get(answerVO.getCommitId());

            // 如果用户的 answerPageVOs 为空，初始化
            if (answerVO1.getAnswerPageVOs() == null)
            {
                List<AnswerPageVO> list = new ArrayList<>();
                answerVO1.setAnswerPageVOs(list);
            }

            // 创建一个新的 AnswerPageVO 对象，并填充数据
            AnswerPageVO answerPageVO = new AnswerPageVO();
            answerPageVO.setAid(answerVO.getAid());
            answerPageVO.setQid(answerVO.getQid());
            answerPageVO.setQueId(answerVO.getQueId());
            answerPageVO.setContent(answerVO.getContent());
            answerPageVO.setType(answerVO.getType());
            answerPageVO.setOptContent(answerVO.getOptContent());
            answerPageVO.setText(answerVO.getText());
            answerPageVO.setCreateTime(answerVO.getCreateTime());

            // 将新的 AnswerPageVO 添加到该用户的 answerPageVOs 列表中
            answerVO1.getAnswerPageVOs().add(answerPageVO);
        });

        answerVOPage.setRecords(new ArrayList<>(map.values()));

        return answerVOPage;
    }

    @Override
    public byte[] export(AnswerExportDTO answerExportDTO) throws IOException {
        QueryWrapper<AnswerVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", answerExportDTO.getUserIds());

        List<AnswerVO> answerVOS = baseMapper.export(answerExportDTO,queryWrapper);


        // 获取问卷所有的问题
        List<String> queContents = new ArrayList<>();
        answerVOS.get(0).getAnswerPageVOs().forEach(answerPageVO -> {
            queContents.add(answerPageVO.getContent());
        });

        // 使用 Apache POI 创建 Excel 工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("问卷数据");
        Row headerRow = sheet.createRow(0);
        int colIndex  = 1;
        for (String queContent : queContents)
        {
            headerRow.createCell(0).setCellValue(queContent); // 问题内容
        }
        // 填充数据行
        int rowIndex = 1;
        for (AnswerVO answerVO : answerVOS)
        {
            Row dataRow = sheet.createRow(rowIndex ++);
            colIndex = 1;
            for (AnswerPageVO answerPageVO : answerVO.getAnswerPageVOs())
            {
                dataRow.createCell(colIndex++).setCellValue(answerPageVO.getOptContent());
            }
        }

        // 写入字节输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        return byteArrayOutputStream.toByteArray();
    }
}
